//
//  ThirdViewController.m
//  lovergotest
//
//  Created by liudonghuan on 14-8-12.
//  Copyright (c) 2014年 liudonghuan. All rights reserved.
//

#import "LGUtil.h"
#import "Photo.h"
#import "DataCenter.h"
#import "UMFeedback.h"
#import "UserTableViewCell.h"
#import "AboutViewController.h"
#import "UserViewController.h"
#import "LoginViewController.h"
//#import "ALLOrderViewController.h"
#import "LGSettingItemController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "OrderViewController.h"
#import "MobClick.h"
#define ORIGINAL_MAX_WIDTH 640.0f

@interface UserViewController ()

@end

@implementation UserViewController

-(id)init
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginNof:) name:loginSPath object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginNof:) name:registerSPath object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginNof:) name:userUpDateSPath object:nil];
    }
    return self;
}
-(void)viewDidUnload
{
    [[NSNotificationCenter defaultCenter] removeObserver:loginSPath name:nil object:self];
    [[NSNotificationCenter defaultCenter] removeObserver:registerSPath name:nil object:self];
    [[NSNotificationCenter defaultCenter] removeObserver:userUpDateSPath name:nil object:self];
}
-(void)loadView
{
    _thirdView = nil;
    _signInView = nil;
    UserInfo *info = [DataCenter getSingleton].userInfo;
    if(info == nil)
    {
        _signInView = [[SignInView alloc] initWithFrame:[LGUtil getViewFrame]];
        _signInView.delegate = self;
        [self setView:_signInView];
    }else
    {
        _thirdView = [[UserView alloc]initWithFrame:[LGUtil getViewFrame]];
        _thirdView.delgete = self;
        _thirdView.meTView.delegate = self;
        _thirdView.meTView.dataSource = self;
        _thirdView.meTView.scrollEnabled = false;
        
        [_thirdView.uNameLab setText:[NSString stringWithFormat:@"%@",info.userName]];
        if ([info.headImg compare:@""] == 0)
        {
            _thirdView.hImgView.image = [LGUtil getUnFoundImage];
        }else{
            _thirdView.hImgView.imageUrl = [NSString stringWithFormat:@"%@lover-go/%@",imagebaseUrl,info.headImg];
        }
        [self setView:_thirdView];
    }
    [LGUtil setTypeWithC:self titleName:nil backName:@"返回"];


}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    UserInfo *info = [DataCenter getSingleton].userInfo;
    [_thirdView.uNameLab setText:[NSString stringWithFormat:@"%@",info.userName]];
    if (info.sex == 0){
        _thirdView.iconUImgView.image = [UIImage imageNamed:@"usercenter_ico_boy.png"];
    }else{
        _thirdView.iconUImgView.image = [UIImage imageNamed:@"usercenter_ico_girl.png"];
    }
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"barBG_blue.png"] forBarMetrics:UIBarMetricsDefault];
    [MobClick beginLogPageView:@"个人中心"];


}
-(void)loginNof:(NSNotification *)nof
{
    if ([[nof name] compare:loginSPath] == 0        ||
        [[nof name] compare:registerSPath] == 0     ||
        [[nof name] compare:userUpDateSPath] == 0
        ) {
        [self loadView];
    }
}

-(void)SignInViewBtnClieck:(SignInType)type
{
    switch (type) {
        case SignInTypeLogin:
        {
            LoginViewController *vc = [[LoginViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        case SignInTypeHelp:
        {
            [UMFeedback showFeedback:self withAppkey:UmengAppkey];
            break;
        }
        case SignInTypeAbout:
        {
            AboutViewController *vc = [[AboutViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        default:
            break;
    }
}

#pragma mark - Table view data source and delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 3;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        NSString *groupName = @" ";
        tableView.sectionHeaderHeight = 20;
        return groupName;
    }else if (section == 1){
        NSString *groupName = @" ";
        tableView.sectionHeaderHeight = 1;
        return groupName;
    }else{
        NSString *groupName = @" ";
        tableView.sectionHeaderHeight = 20;
        return groupName;
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UserTableViewCell * cell;
    switch (indexPath.section) {
        case 0:
        {
            cell = [[UserTableViewCell alloc] initWithLabel:@"版本检查"];
            break;
        }
        case 1:
        {
            cell = [[UserTableViewCell alloc] initWithLabel:@"意见反馈"];
            break;
        }
        case 2:
        {
            cell = [[UserTableViewCell alloc] initWithLabel:@"关于情侣去哪儿"];
            break;
        }
        default:
            cell = [[UserTableViewCell alloc] init];
            break;
    }
    return cell;
}
#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    if (_thirdView) {
        _thirdView.hImgView.image = editedImage;
    }
    NSString *imageString=[Photo image2String:editedImage];
    
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        //上传图片
        NSMutableDictionary *para = [[NSMutableDictionary alloc] init];
        [para setObject:[DataCenter getSingleton].userInfo.uuid forKey:@"appUser.uuid"];
        [para setObject:imageString forKey:@"photo"];
        
        SVHTTPClient *svc = [[SVHTTPClient alloc] init];
        [svc POST:@"http://123.57.7.162:8588/lover-go/appUser/update" parameters:para completion:^(id response, NSHTTPURLResponse *urlResponse, NSError *error) {
            [[[[UIApplication sharedApplication] delegate] window] makeToast:@"上传头像成功"
                                                                    duration:1.0
                                                                    position:@"center"];
            return;

        }];
    }];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            [MobClick checkUpdate];
            break;
        }
        case 1:
        {
            [UMFeedback showFeedback:self withAppkey:UmengAppkey];
            break;
        }
        case 2:
        {
            AboutViewController *vc = [[AboutViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }

            
        default:
            break;
    }
}
-(void)gerenxinxiBtnClick
{
    LGSettingItemController *vc = [[LGSettingItemController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)dingdanBtnClick
{
    OrderViewController *_huoDongDetailController = [[OrderViewController alloc]init];
    self.navigationItem.backBarButtonItem = [LGUtil getBackButton];
    [self.navigationController pushViewController:_huoDongDetailController animated:YES];
}
//左右滑动
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if (scrollView.contentOffset.y>-30) {
        
    }else if(scrollView.contentOffset.x<50){
        
    }
    
}


-(void)UserViewBtnClieck:(UserViewType)type
{
    if (type == TypeChangeImg) {
        
        self.actionSheet = [[LXActionSheet alloc]initWithTitle:@"上传头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@[@"从相册中选取"]];
        self.actionSheet.tag = 2;
        [self.actionSheet showInView:self.view];
    }else{
        self.actionSheet = [[LXActionSheet alloc]initWithTitle:@"退出后不会删除任何历史数据,下次登录依然可以使用本账号" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"退出登录" otherButtonTitles:nil];
        self.actionSheet.tag = 1;
        [self.actionSheet showInView:self.view];
    }
}
#pragma mark - LXActionSheetDelegate

- (void)didClickOnButtonIndex:(NSInteger *)buttonIndex
{
    if (self.actionSheet.tag == 2) {
        if ((int)buttonIndex == 1) {
            // 从相册中选取
            if ([self isPhotoLibraryAvailable]) {
                UIImagePickerController *controller = [[UIImagePickerController alloc] init];
                controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
                [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
                controller.mediaTypes = mediaTypes;
                controller.delegate = self;
                [self presentViewController:controller
                                   animated:YES
                                 completion:^(void){
                                     NSLog(@"Picker View Controller is presented");
                                 }];
            }
        }
    }
}

- (void)didClickOnDestructiveButton
{
    if (self.actionSheet.tag == 1) {
        [[DataCenter getSingleton] signOut];
        [self loadView];
    }else if (self.actionSheet.tag == 2){
        // 拍照
        if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            if ([self isFrontCameraAvailable]) {
                controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            }
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
    }
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [self imageByScalingToMaxSize:portraitImg];
        // 裁剪
        VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:3.0];
        imgEditorVC.delegate = self;
        [self presentViewController:imgEditorVC animated:YES completion:^{
            // TO DO
        }];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
}
#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"个人中心"];
}
@end
